package com.itheima.ydd.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.dto.RoleDto;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.RoleMenu;
import com.itheima.ydd.mapper.RoleMapper;
import com.itheima.ydd.service.RoleMenuService;
import com.itheima.ydd.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author yan.zhou
 * @since 2022-02-22
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    @Autowired
    private RoleMenuService roleMenuService;


    @Override
    public List<String> roleNameList(String role_id) {
        String[] strings = role_id.split(",");
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(Role::getId, strings);
        List<Role> roles = this.list(roleLambdaQueryWrapper);
        List<String> roleNameList = CollUtil.getFieldValues(roles, "name", String.class);
        return roleNameList;
    }

    /**
     * 修改权限
     * @param roleDto
     */
    @Override
    //开启事务
    @Transactional
    public void updateRoleAndMenu(RoleDto roleDto) {

        this.updateById(roleDto);

        //删除该ID下所以菜单
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRole_id,roleDto.getId());
        roleMenuService.remove(queryWrapper);
        //新增菜单
        List<String> ids = roleDto.getMenuids();
        for (String id : ids) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenu_id(id);
            roleMenu.setRole_id(roleDto.getId());
            roleMenuService.save(roleMenu);
        }

    }
}
